<template>
  <a-card>
    <div :class="advanced ? 'search' : null">
      <a-form layout="horizontal">
        <div :class="advanced ? null: 'fold'">
          <a-row>
            <a-col :md="8" :sm="24">
              <a-form-item
                  :labelCol="{span: 5}"
                  :wrapperCol="{span: 18, offset: 1}"
                  label="角色名/说明"
              >
                <a-input v-model="search.keyword" placeholder="请输入"/>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <span style="float: right; margin-top: 3px;">
          <a-button type="primary" @click="searchData">查询</a-button>
          <a-button style="margin-left: 8px">重置</a-button>
        </span>
      </a-form>
    </div>
    <div>
      <a-space class="operator">
        <a-button type="primary" @click="showRoleModal">新建</a-button>
      </a-space>
      <a-table :columns="columns" :data-source="dataSource" :pagination="pagination" row-key="id"
               @change="changePageNo">
        <template slot="action" slot-scope="text,record,index">
          <a style="margin-right: 8px" @click="showPermModal(record,index)">
            <a-icon type="edit"/>
            设置权限</a>
          <a style="margin-right: 8px" @click="editRole(record,index)">
            <a-icon type="edit"/>
            编辑</a>
          <a style="margin-right: 8px" @click="lockRole(record)">
            <a-icon type="delete"/>
            {{ record.status === 'NORMAL' ? "锁定" : "解锁" }}</a>
        </template>
      </a-table>
      <a-modal v-model="roleModal" on-ok="saveRole" title="新增/编辑">
        <template slot="footer">
          <a-button key="back" @click="hideRoleModal">取消</a-button>
          <a-button key="submit" type="primary" @click="saveRole">保存</a-button>
        </template>
        <a-form-model
            ref="ruleForm"
            :label-col="{span: 7}"
            :model="form"
            :rules="rules"
            :wrapper-col="{span: 10}"
        >
          <a-form-model-item ref="name" :labelCol="{span: 5}" :wrapperCol="{span: 15}" label="角色名" prop="name">
            <a-input v-model="form.name"
                     placeholder="请输入角色名"
                     @blur="() => {$refs.name.onFieldBlur();}"/>
          </a-form-model-item>

          <a-form-model-item ref="note" :labelCol="{span: 5}" :wrapperCol="{span: 15}" label="角色说明" prop="note">
            <a-input v-model="form.note" placeholder="请输入角色说明"
                     type="textarea"
                     @blur="() => {$refs.note.onFieldBlur();}"/>
          </a-form-model-item>
        </a-form-model>
      </a-modal>

      <a-modal v-model="permModal" title="设置权限">
        <template slot="footer">
          <a-button key="back" @click="hidePermModal">取消</a-button>
          <a-button key="submit" type="primary" @click="saveRole">保存</a-button>
        </template>
        <a-tree
            v-model="permTree"
            :auto-expand-parent="autoExpandParent"
            :expanded-keys="expandedKeys"
            :selected-keys="selectedKeys"
            :tree-data="treeData"
            checkable
            @expand="expandPermTree"
            @select="selectPermTree"
        />
      </a-modal>
    </div>
  </a-card>
</template>

<script>
import {LIST_ROLE, COUNT_ROLE, CREATE_ROLE, LOCK_ROLE, GET_PERMISSION} from '@/services/api'
import {METHOD, request} from '@/utils/request'

const columns = [
  {
    title: '角色ID',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '角色名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '角色说明',
    dataIndex: 'note',
    key: 'note',
  },
  {
    title: '状态',
    dataIndex: 'statusDisplayName',
    key: 'status',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
  },
  {
    title: '更新人',
    dataIndex: 'updateBy',
    key: 'updateBy',
  },
  {
    title: '操作',
    scopedSlots: {customRender: 'action'}
  }
]

const dataSource = []

export default {
  name: 'RoleList',
  data() {
    return {
      advanced: false,
      columns: columns,
      dataSource: dataSource,
      treeData: [],
      selectedKeys: [],
      expandedKeys: [],
      permTree: [],
      autoExpandParent: true,
      roleModal: false,
      permModal: false,
      pagination: {
        pageSizeOptions: ['10', '50', '100', '500'],
        showSizeChanger: true,
        pageSize: 10,
        total: 0,
        defaultCurrent: 1,
        showTotal: total => `总${total}条`,
      },
      selectedRows: [],
      search: {
        keyword: '',
        auth: ''
      },
      form: {
        name: '',
        note: ''
      },
      rules: {
        name: [
          {type: 'string', required: true, message: '请填写角色名称', trigger: 'blur'},
          {min: 1, max: 64, message: '角色名称不能超过64个字', trigger: 'blur'},
        ],
        note: [
          {type: 'string', required: false, message: '请填写权限说明', trigger: 'blur'},
          {min: 0, max: 128, message: '权限别名不能超过128个字', trigger: 'blur'},
        ]
      },
    }
  },
  watch: {
    permTree(val) {
      console.log('onCheck', val);
    }
  },
  methods: {
    showRoleModal() {
      this.roleModal = true;
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
      })
    },
    hideRoleModal() {
      this.roleModal = false;
    },
    showPermModal() {
      this.permModal = true;
      request(GET_PERMISSION, METHOD.POST, {}).then(result => {
        if (result.data.code === "SUCCESS") {
          const respData = result.data.data;
          const itemData = this.convertTreeData(respData);
          console.log(JSON.stringify(itemData));
          this.treeData = itemData;
          console.log(this.treeData);
        } else {
          this.$message.success(result.data.msg, 3)
        }
      })
    },
    convertTreeData(respData) {
      const itemData = [];
      respData.forEach(item => {
        itemData.push({
          key: item.id,
          title: item.name,
          children: this.convertTreeData(item.children)
        });
      });
      return itemData;
    },
    hidePermModal() {
      this.permModal = false;
    },
    expandPermTree(expandedKeys) {
      console.log('onExpand', expandedKeys);
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    selectPermTree(selectedKeys, info) {
      console.log('onSelect', info);
      this.selectedKeys = selectedKeys;
    },
    checkPermTree(checkedKeys) {
      console.log('onCheck', checkedKeys);
      this.checkedKeys = checkedKeys;
    },
    saveRole() {
      console.log('form ->value')
      console.log(this.form);
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          console.log(this.form);

          const options = this.form;
          console.log('options')
          console.log(options)
          request(CREATE_ROLE, METHOD.POST, options).then(result => {
            if (result.data.code === "SUCCESS") {
              this.$message.success("保存成功", 5)
              this.roleModal = false;
              this.loadData();
            } else {
              this.$message.error(result.data.msg, 5)
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    changePageNo(pagination) {
      console.log(pagination);
      const pager = {...this.pagination};
      pager.current = pagination.current;
      pager.pageSize = pagination.pageSize;
      this.pagination = pager;
      this.loadData();
    },
    searchData() {
      this.loadData();
      this.countData();
    },
    loadData() {
      console.log(this.search.keyword);
      console.log(this.pagination);
      const options = {
        page: this.pagination.current,
        size: this.pagination.pageSize,
        keyword: this.search.keyword
      }
      request(LIST_ROLE, METHOD.POST, options).then(result => {
        console.log(result.data);
        if (result.data.code === "SUCCESS") {
          this.dataSource = new Array();
          const respData = result.data.data;
          respData.forEach(item => {
            this.dataSource.push(item)
            // this.dataSource.push({
            //   key: item.id,
            //   id: item.id,
            //   name: item.name,
            //   note: item.note,
            //   statusDisplayName: item.statusDisplayName,
            //   updateTime: item.updateTime,
            //   updateBy: item.updateBy
            // })
          })
        } else {
          this.$message.success(result.data.msg, 3)
        }
      })
    },
    countData() {
      const options = {
        keyword: this.search.keyword
      }
      request(COUNT_ROLE, METHOD.POST, options).then(result => {
        console.log(result.data);
        if (result.data.code === "SUCCESS") {
          this.pagination.total = result.data.data;
        } else {
          this.$message.success(result.data.msg, 3)
        }
      })
    },
    editRole(rowData) {
      this.showRoleModal();
      this.form = rowData;
      console.log(this.form);
    },
    lockRole(rowData) {
      console.log(rowData);
      const options = {
        id: rowData.id,
        status: rowData.status === 'NORMAL' ? "LOCKED" : "NORMAL"
      }
      request(LOCK_ROLE, METHOD.POST, options).then(result => {
        if (result.data.code === "SUCCESS") {
          if (rowData.status === 'NORMAL') {
            rowData.status = 'LOCKED';
            this.$message.success("锁定成功", 3);
          } else {
            rowData.status = 'NORMAL';
            this.$message.success("解锁成功", 3);
          }
        } else {
          this.$message.error(result.data.msg, 5)
        }
      })
    },
  },
  created() {
    this.loadData();
    this.countData();
  }
}
</script>

<style lang="less" scoped>
.search {
  margin-bottom: 54px;
}

.fold {
  width: calc(100% - 216px);
  display: inline-block
}

.operator {
  margin-bottom: 18px;
}

@media screen and (max-width: 900px) {
  .fold {
    width: 100%;
  }
}
</style>
